package com.xtx.json;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * A JsonTokener takes a source string and extracts characters and tokens from
 * it. It is used by the JsonObject and JsonArray constructors to parse JSON
 * source strings.
 * 
 * @author JSON.org
 * @version 2007-12-5
 */
public class JsonTokener {
    private int index;

    private String source;

    /**
     * Construct a JsonTokener from a string.
     * 
     * @param str A source string
     */
    public JsonTokener(String str) {
        this.index = 0;
        this.source = str;
    }

    /**
     * Construct a JsonTokener from a reader.
     * 
     * @param reader A source reader
     */
    public JsonTokener(BufferedReader reader) throws JsonException {
        this.index = 0;
        try {
            StringBuffer json = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
            this.source = json.toString();
        } catch (IOException e) {
            throw new JsonException(e.getCause());
        }
    }

    protected void back() {
        if (this.index > 0) {
            this.index -= 1;
        }
    }

    protected char next() {
        if (this.index < this.source.length()) {
            char chr = this.source.charAt(this.index);
            this.index += 1;
            return chr;
        }
        return 0;
    }

    protected String next(int n) throws JsonException {
        int i = this.index;
        int j = i + n;
        if (j >= this.source.length()) {
            throw new JsonException("Substring bounds error");
        }
        this.index += n;
        return this.source.substring(i, j);
    }

    /**
     * Get the next char in the string, skipping whitespace and comments.
     * 
     * @return A character, or 0 if there are no more characters
     * @throws JsonException
     */
    protected char nextClean() throws JsonException {
        while (true) {
            char chr = next();
            if (chr == '/') {
                switch (next()) {
                    case '/':
                        do {
                            chr = next();
                        } while (chr != '\n' && chr != '\r' && chr != 0);
                        break;
                    case '*':
                        while (true) {
                            chr = next();
                            if (chr == 0) {
                                throw new JsonException("Unclosed comment");
                            }
                            if (chr == '*') {
                                if (next() == '/') {
                                    break;
                                }
                                back();
                            }
                        }
                        break;
                    default:
                        back();
                        return '/';
                }
            } else if (chr == '#') {
                do {
                    chr = next();
                } while (chr != '\n' && chr != '\r' && chr != 0);
            } else if (chr == 0 || chr > ' ') {
                return chr;
            }
        }
    }

    /**
     * Return the characters up to the next close quote character.
     * 
     * @param quote The quoting character
     * @return A String
     * @throws JsonException
     */
    protected String nextString(char quote) throws JsonException {
        char chr;
        StringBuffer strb = new StringBuffer();
        while (true) {
            chr = next();
            switch (chr) {
                case 0:
                case '\n':
                case '\r':
                    throw new JsonException("Unterminated string");
                case '\\':
                    chr = next();
                    switch (chr) {
                        case 'b':
                            strb.append('\b');
                            break;
                        case 't':
                            strb.append('\t');
                            break;
                        case 'n':
                            strb.append('\n');
                            break;
                        case 'f':
                            strb.append('\f');
                            break;
                        case 'r':
                            strb.append('\r');
                            break;
                        case 'u':
                            strb.append((char) Integer.parseInt(next(4), 16));
                            break;
                        case 'x':
                            strb.append((char) Integer.parseInt(next(2), 16));
                            break;
                        default:
                            strb.append(chr);
                    }
                    break;
                default:
                    if (chr == quote) {
                        return strb.toString();
                    }
                    strb.append(chr);
            }
        }
    }

    /**
     * Get the next value. The value can be a Boolean, Double, Integer,
     * JsonArray, JsonObject, Long, or String, or the JsonObject.NULL object.
     * 
     * @return An object
     * @throws JsonException
     */
    protected Object nextValue() throws JsonException {
        char chr = nextClean();
        switch (chr) {
            case '"':
            case '\'':
                return nextString(chr);
            case '{':
                back();
                return new JsonObject(this);
            case '[':
                back();
                return new JsonArray(this);
        }
        StringBuffer strb = new StringBuffer();
        char num = chr;
        while (chr >= ' ' && ",:]}/\\\"[{;=#".indexOf(chr) < 0) {
            strb.append(chr);
            chr = next();
        }
        back();
        String str = strb.toString().trim();
        if (str.equals("")) {
            throw new JsonException("Missing value");
        }
        if (str.equalsIgnoreCase("true")) {
            return Boolean.TRUE;
        }
        if (str.equalsIgnoreCase("false")) {
            return Boolean.FALSE;
        }
        if (str.equalsIgnoreCase("null")) {
            return null;
        }
        if ((num >= '0' && num <= '9') || num == '.' || num == '-' || num == '+') {
            if (num == '0') {
                if (str.length() > 2 && (str.charAt(1) == 'x' || str.charAt(1) == 'X')) {
                    try {
                        return new Integer(Integer.parseInt(str.substring(2), 16));
                    } catch (Exception e) {}
                } else {
                    try {
                        return new Integer(Integer.parseInt(str, 8));
                    } catch (Exception e) {}
                }
            }
            try {
                return new Integer(str);
            } catch (Exception e) {
                try {
                    return new Long(str);
                } catch (Exception f) {
                    try {
                        return new Double(str);
                    } catch (Exception g) {
                        return str;
                    }
                }
            }
        }
        return str;
    }
}